import md5Libs from 'uview-ui/libs/function/md5'
const tencentLocationKey = 'U4JBZ-ZWGRX-3XI4S-ZSMA6-WBKJK-JQBHO' // 腾讯位置key
const secretKey = 'XCYZaphIt6bDnlAqXva9j8A99Ius1jC' // 密钥
/**
 * 经纬度 换 位置描述 (逆地址解析)
 **/
const reverseGeocoder = (latitude, longitude) => {
	return new Promise((resolve, reject) => {
		const sig = md5Libs.md5(
			`/ws/geocoder/v1/?key=${tencentLocationKey}&location=${latitude},${longitude}${secretKey}`)
		const url =
			`https://apis.map.qq.com/ws/geocoder/v1/?key=${tencentLocationKey}&location=${latitude},${longitude}&sig=${sig}`
		uni.request({
			url,
			success: (res) => {
				if (res.data.status == 0) {
					console.log('请求成功', res)
					resolve(res.data)
				} else {
					console.log('请求失败', res)
					reject(res.data.message)
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}
/**
 * 详细地址 换 经纬度 （地址解析）
 **/
const geocoder = (address) => {
	address = address.replace(/\+ ?/g,
		'') // 猜测md5加密“+”后得到的sig与腾讯地图的不一致，导致签名认证失败，所以直接过滤掉“+”再进行签名认证（暂时只发现“+”会导致此问题，后期发现别的再加）
	return new Promise((resolve, reject) => {
		const sig = md5Libs.md5(`/ws/geocoder/v1/?address=${address}&key=${tencentLocationKey}${secretKey}`)
		const url =
			`https://apis.map.qq.com/ws/geocoder/v1/?address=${encodeURIComponent(address)}&key=${tencentLocationKey}&sig=${sig}`
		uni.request({
			url,
			success: (res) => {
				if (res.data.status == 0) {
					console.log('请求成功', res)
					resolve(res.data)
				} else {
					console.log('请求失败', res)
					reject(res.data.message)
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}

// setSession('userInfo', JSON.stringify(res.body))
// 存储sessionstorage数据
const setSession = (key, data) => {
	if (window.sessionStorage) {
		const sStorage = window.sessionStorage
		sStorage.setItem(key, data)
	}
}

// getSession('userInfo')
// 获取sessionstorage数据
const = getSession(key) => {
	if (window.sessionStorage) {
		const sStorage = window.sessionStorage
		const data = JSON.parse(sStorage.getItem(key))
		for (const key in data) {
			if (data[key] === 'null') {
				data[key] = ''
			}
		}
		return data
	}
}

// selSession('userInfo')
// 删除sessionstorage数据
const = selSession(key) => {
	if (window.sessionStorage) {
		const sStorage = window.sessionStorage
		sStorage.removeItem(key)
	}
}

const formateNumber = function(val) {
	val = Number(val)
	if (parseInt(val) === val) {
		return parseInt(val)
	} else {
		return Number(toFixed(val, 2))
	}
}


const toFixed = function(cur, d) {
	let s = cur + ''
	let fixedValue = ''
	if (!d) d = 0
	if (s.indexOf('.') == -1) s += '.'
	s += new Array(d + 1).join('0')
	if (new RegExp('^(-|\\+)?(\\d+(\\.\\d{0,' + (d + 1) + '})?)\\d*$').test(s)) {
		let s = '0' + RegExp.$2
		const pm = RegExp.$1
		const a = RegExp.$3.length
		let b = true
		if (a === d + 2) {
			const reg = s.match(/\d/g)
			if (parseInt(reg[reg.length - 1], 0) > 4) {
				for (let i = reg.length - 2; i >= 0; i--) {
					reg[i] = `${parseInt(reg[i], 0) + 1}`
					if (reg[i] == '10') {
						reg[i] = '0'
						b = i !== 1
					} else break
				}
			}
			s = reg.join('').replace(new RegExp('(\\d+)(\\d{' + d + '})\\d$'), '$1.$2')
		}
		if (b) s = s.substr(1)
		fixedValue = (pm + s).replace(/\.$/, '')
	} else {
		fixedValue = cur + ''
	}

	// 拷贝一份 返回去掉零的新串
	let newstr = fixedValue
	// 循环变量 小数部分长度
	const leng = fixedValue.length - fixedValue.indexOf('.') - 1
	// 判断是否有效数
	if (fixedValue.indexOf('.') > -1) {
		// 循环小数部分
		for (let i = leng; i > 0; i--) {
			// 如果newstr末尾有0
			if (newstr.lastIndexOf('0') > -1 && newstr.substr(newstr.length - 1, 1) === '0') {
				const k = newstr.lastIndexOf('0')
				// 如果小数点后只有一个0 去掉小数点
				if (newstr.charAt(k - 1) === '.') {
					return newstr.substring(0, k - 1)
				} else {
					// 否则 去掉一个0
					newstr = newstr.substring(0, k)
				}
			} else {
				// 如果末尾没有0
				return newstr
			}
		}
	}
	return fixedValue
}



// Vue.prototype.$throttle = throttle
// Vue.prototype.$debounce = debounce
// this.handlePay = this.$debounce(this.handlePay, 1500, { trailing: false })
// this.updateWalletInfo = this.$throttle(this.updateWalletInfo, 1000, { trailing: false })

/**
 * 频率控制函数， fn执行次数不超过 1 次/wait
 * @desc 函数节流
 * @param func 函数
 * @param wait 延迟执行毫秒数
 * @param type 1 表时间戳版，2 表定时器版
 * @returns {Function}     返回调用函数
 */
export function throttle(fn, delay, options) {
	var wait = false
	options = options || {}
	return function() {
		var that = this
		var args = arguments
		if (!wait) {
			if (!(options.leading === false)) {
				fn.apply(that, args)
			}
			wait = true
			setTimeout(function() {
				if (!(options.trailing === false)) {
					fn.apply(that, args)
				}
				wait = false
			}, delay)
		}
	}
}
/**
 * 空闲控制函数， fn仅执行一次
 * @param fn{Function}     传入的函数
 * @param delay{Number}    时间间隔
 * @param options{Object}  如果想忽略开始边界上的调用则传入 {leading:false},
 *                         如果想忽略结束边界上的调用则传入 {trailing:false},
 * @returns {Function}     返回调用函数
 */
export function debounce(fn, delay, options) {
	var timeoutId
	var leadingExc = false
	options = options || {}

	return function() {
		var that = this
		var args = arguments
		if (!leadingExc && !(options.leading === false)) {
			fn.apply(that, args)
		}
		leadingExc = true
		if (timeoutId) {
			clearTimeout(timeoutId)
		}

		timeoutId = setTimeout(function() {
			if (!(options.trailing === false)) {
				fn.apply(that, args)
			}
			leadingExc = false
		}, delay)
	}
}

/* eslint-disable */

// new Date().Format('yyyy-MM-dd')
// new Date().Format('yyyy-MM-dd hh:mm:ss')
Date.prototype.Format = function(fmt) {
	var o = {
		'M+': this.getMonth() + 1,
		'd+': this.getDate(),
		'h+': this.getHours(),
		'm+': this.getMinutes(),
		's+': this.getSeconds(),
		'q+': Math.floor((this.getMonth() + 3) / 3),
		'S': this.getMilliseconds()
	}
	if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length))
	for (var k in o)
		if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : ((
			'00' + o[k]).substr(('' + o[k]).length)))
	return fmt
}


export const getQueryObject = function(url) {
	var search = url;
	var obj = {};
	var reg = /([^?#&=]+)=([^&]*)/g;
	search.replace(reg, function(rs, $1, $2) {
		var name = decodeURIComponent($1);
		var val = decodeURIComponent($2);
		val = String(val);
		obj[name] = val;
		return rs;
	});
	return obj;
}

// timeDiff('2021-7-14','2021-8-20')
// "37天00时00分00秒"
// timeDiff('2021-7-14 08:20:00','2021-8-20 20:51:40')
// "37天12时31分40秒"
const timeDiff = (time, endTime) => {
	try {
		if (!time) return ''
		const timeNowtamp = endTime ?
			new Date(endTime.replace(/-/g, '/')).getTime() :
			new Date().getTime() // 当前时间毫秒数
		const timestamp = new Date(time.replace(/-/g, '/')).getTime() // 传值时间毫秒数
		if (timestamp > timeNowtamp) return ''
		const diiftime = (timeNowtamp - timestamp) / 1000
		let [day, hour, minute, second] = [0, 0, 0, 0]
		day = Math.floor(diiftime / (60 * 60 * 24))
		hour = Math.floor(diiftime / (60 * 60)) - day * 24
		minute = Math.floor(diiftime / 60) - hour * 60 - day * 24 * 60
		second =
			Math.floor(diiftime) - day * 24 * 60 * 60 - hour * 60 * 60 - minute * 60
		hour = hour < 10 ? '0' + hour : hour
		minute = minute < 10 ? '0' + minute : minute
		second = second < 10 ? '0' + second : second
		return `${day}天${hour}时${minute}分${second}秒`
	} catch (e) {
		return ''
	}
}


module.exports = {
	openSetting,
	getSetting,
	getProvider,
	formateNumber,
	ZYtoFixed,
	debounce,
	throttle,
	getQueryObject,
	reverseGeocoder,
	geocoder
}
